<?php
require_once __DIR__ . '/functions.php';

// 检查登录
if (!isLoggedIn()) {
    redirect('index.php', '请先登录', 'warning');
}

$userInfo = getUserInfo();

// 获取群组选项
$groupOptions = getConfigOptions('group_name');

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? '';
    $csrf_token = $_POST['csrf_token'] ?? '';
    
    // 验证CSRF令牌
    if (!validateCsrfToken($csrf_token)) {
        $error = '安全令牌无效，请刷新页面重试';
    } elseif ($action == 'update_profile') {
        // 更新基本信息
        $username = sanitizeInput($_POST['username'] ?? '');
        $phone = sanitizeInput($_POST['phone'] ?? '');
        $wechat_account = sanitizeInput($_POST['wechat_account'] ?? '');
        $alipay_account = sanitizeInput($_POST['alipay_account'] ?? '');
        $group_name = sanitizeInput($_POST['group_name'] ?? '');
        $wechat_nickname = sanitizeInput($_POST['wechat_nickname'] ?? '');
        $account_holder = sanitizeInput($_POST['account_holder'] ?? '');
        $bank_name = sanitizeInput($_POST['bank_name'] ?? '');
        $bank_card_number = sanitizeInput($_POST['bank_card_number'] ?? '');
        
        if (empty($username) || empty($phone) || empty($wechat_account) || empty($alipay_account) || 
            empty($group_name) || empty($account_holder) || empty($bank_name) || empty($bank_card_number)) {
            $error = '所有带星号(*)的字段都是必填项';
        } elseif (!validatePhone($phone)) {
            $error = '手机号格式不正确';
        } elseif (!validateBankCard($bank_card_number)) {
            $error = '银行卡号格式不正确';
        } else {
            $db = getDB();
            
            // 检查用户名是否被其他用户使用
            $stmt = $db->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
            $stmt->execute([$username, $userInfo['id']]);
            if ($stmt->fetch()) {
                $error = '该用户名已被使用';
            } else {
                // 检查手机号是否被其他用户使用
                $stmt = $db->prepare("SELECT id FROM users WHERE phone = ? AND id != ?");
                $stmt->execute([$phone, $userInfo['id']]);
                if ($stmt->fetch()) {
                    $error = '该手机号已被使用';
                } else {
                    $stmt = $db->prepare("UPDATE users SET username = ?, phone = ?, wechat_account = ?, alipay_account = ?, group_name = ?, wechat_nickname = ?, account_holder = ?, bank_name = ?, bank_card_number = ? WHERE id = ?");
                    if ($stmt->execute([$username, $phone, $wechat_account, $alipay_account, $group_name, $wechat_nickname, $account_holder, $bank_name, $bank_card_number, $userInfo['id']])) {
                        $_SESSION['username'] = $username;
                        logSecurityEvent('profile_updated', $userInfo['id']);
                        $success = '基本信息更新成功';
                        $userInfo = getUserInfo(); // 重新获取用户信息
                    } else {
                        $error = '更新失败，请重试';
                    }
                }
            }
        }
    } elseif ($action == 'change_password') {
        // 修改密码
        $old_password = $_POST['old_password'] ?? '';
        $new_password = $_POST['new_password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';
        
        if (empty($old_password) || empty($new_password)) {
            $error = '请填写完整的密码信息';
        } elseif ($new_password !== $confirm_password) {
            $error = '新密码两次输入不一致';
        } elseif (strlen($new_password) < 8) {
            $error = '新密码长度不能少于8位';
        } else {
            if (!passwordVerify($old_password, $userInfo['password'])) {
                $error = '原密码错误';
            } else {
                $db = getDB();
                $hashedPassword = passwordHash($new_password);
                $stmt = $db->prepare("UPDATE users SET password = ? WHERE id = ?");
                if ($stmt->execute([$hashedPassword, $userInfo['id']])) {
                    logSecurityEvent('password_changed', $userInfo['id']);
                    $success = '密码修改成功';
                } else {
                    $error = '密码修改失败，请重试';
                }
            }
        }
    } elseif ($action == 'update_qr') {
        // 更新收款码
        $qr_type = $_POST['qr_type'] ?? '';
        
        if (!isset($_FILES['qr_image']) || $_FILES['qr_image']['error'] !== UPLOAD_ERR_OK) {
            $error = '请选择要上传的图片';
        } else {
            $uploadResult = uploadFile($_FILES['qr_image'], 'qr_code');
            
            if ($uploadResult['success']) {
                $db = getDB();
                $field = $qr_type == 'wechat' ? 'wechat_qr' : 'alipay_qr';
                
                // 删除旧图片
                if ($userInfo[$field]) {
                    deleteFile($userInfo[$field], 'qr_code');
                }
                
                $stmt = $db->prepare("UPDATE users SET $field = ? WHERE id = ?");
                if ($stmt->execute([$uploadResult['filename'], $userInfo['id']])) {
                    logSecurityEvent('qr_code_updated', $userInfo['id'], "类型: $qr_type");
                    $success = ($qr_type == 'wechat' ? '微信' : '支付宝') . '收款码更新成功';
                    $userInfo = getUserInfo(); // 重新获取用户信息
                } else {
                    // 删除上传的文件
                    deleteFile($uploadResult['filename'], 'qr_code');
                    $error = '收款码更新失败，请重试';
                }
            } else {
                $error = $uploadResult['message'];
            }
        }
    } elseif ($action == 'update_pushplus') {
        // 更新PushPlus设置
        $pushplus_token = sanitizeInput($_POST['pushplus_token'] ?? '');
        $pushplus_enabled = isset($_POST['pushplus_enabled']) ? 1 : 0;
        
        if ($pushplus_enabled && empty($pushplus_token)) {
            $error = '开启推送通知需要填写PushPlus密钥';
        } else {
            $db = getDB();
            $stmt = $db->prepare("UPDATE users SET pushplus_token = ?, pushplus_enabled = ? WHERE id = ?");
            if ($stmt->execute([$pushplus_token, $pushplus_enabled, $userInfo['id']])) {
                logSecurityEvent('pushplus_updated', $userInfo['id']);
                $success = 'PushPlus设置更新成功';
                $userInfo = getUserInfo(); // 重新获取用户信息
            } else {
                $error = 'PushPlus设置更新失败，请重试';
            }
        }
    }
}

include __DIR__ . '/header.php';
?>

<div class="container">
    <div class="row">
        <div class="col-lg-10 mx-auto">
            <div class="card shadow">
                <div class="card-header bg-primary text-white">
                    <h4 class="mb-0">
                        <i class="bi bi-person-circle"></i> 个人资料
                    </h4>
                </div>
                <div class="card-body">
                    <?php if (isset($error)): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="bi bi-exclamation-triangle-fill"></i> <?php echo htmlspecialchars($error); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (isset($success)): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="bi bi-check-circle-fill"></i> <?php echo htmlspecialchars($success); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <!-- 基本信息 -->
                    <div class="mb-5">
                        <h5 class="border-bottom pb-2 mb-3">
                            <i class="bi bi-info-circle"></i> 基本信息 <small class="text-muted">（带<span class="text-danger">*</span>为必填项）</small>
                        </h5>
                        <form method="POST" class="needs-validation" novalidate>
                            <input type="hidden" name="action" value="update_profile">
                            <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="username" class="form-label">用户名 <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="username" name="username" 
                                               value="<?php echo htmlspecialchars($userInfo['username']); ?>" required>
                                        <div class="invalid-feedback">
                                            请输入用户名
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="phone" class="form-label">手机号 <span class="text-danger">*</span></label>
                                        <input type="tel" class="form-control" id="phone" name="phone" 
                                               value="<?php echo htmlspecialchars($userInfo['phone']); ?>" required pattern="^1[3-9]\d{9}$">
                                        <div class="invalid-feedback">
                                            请输入正确的手机号
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="group_name" class="form-label">
                                            <i class="bi bi-people text-primary"></i> 所在群组 <span class="text-danger">*</span>
                                        </label>
                                        <select class="form-select" id="group_name" name="group_name" required>
                                            <option value="">请选择所在群组</option>
                                            <?php foreach ($groupOptions as $group): ?>
                                                <option value="<?php echo htmlspecialchars($group['option_value']); ?>" 
                                                        <?php echo ($userInfo['group_name'] ?? '') == $group['option_value'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($group['option_label']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <div class="invalid-feedback">
                                            请选择所在群组
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="wechat_nickname" class="form-label">
                                            <i class="bi bi-wechat text-success"></i> 微信名称
                                        </label>
                                        <input type="text" class="form-control" id="wechat_nickname" name="wechat_nickname" 
                                               value="<?php echo htmlspecialchars($userInfo['wechat_nickname'] ?? ''); ?>" 
                                               placeholder="请输入您的微信名称">
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="wechat_account" class="form-label">
                                            <i class="bi bi-wechat text-success"></i> 微信号 <span class="text-danger">*</span>
                                        </label>
                                        <input type="text" class="form-control" id="wechat_account" name="wechat_account" 
                                               value="<?php echo htmlspecialchars($userInfo['wechat_account'] ?? ''); ?>" 
                                               placeholder="请输入您的微信号" required>
                                        <div class="invalid-feedback">
                                            请输入微信号
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="alipay_account" class="form-label">
                                            <i class="bi bi-alipay text-primary"></i> 支付宝账号 <span class="text-danger">*</span>
                                        </label>
                                        <input type="text" class="form-control" id="alipay_account" name="alipay_account" 
                                               value="<?php echo htmlspecialchars($userInfo['alipay_account'] ?? ''); ?>" 
                                               placeholder="请输入您的支付宝账号" required>
                                        <div class="invalid-feedback">
                                            请输入支付宝账号
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="account_holder" class="form-label">
                                            <i class="bi bi-person-badge text-primary"></i> 开户人姓名 <span class="text-danger">*</span>
                                        </label>
                                        <input type="text" class="form-control" id="account_holder" name="account_holder" 
                                               value="<?php echo htmlspecialchars($userInfo['account_holder'] ?? ''); ?>" 
                                               placeholder="请输入银行卡开户人姓名" required>
                                        <div class="invalid-feedback">
                                            请输入开户人姓名
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="bank_name" class="form-label">
                                            <i class="bi bi-bank text-primary"></i> 银行名称 <span class="text-danger">*</span>
                                        </label>
                                        <input type="text" class="form-control" id="bank_name" name="bank_name" 
                                               value="<?php echo htmlspecialchars($userInfo['bank_name'] ?? ''); ?>" 
                                               placeholder="请输入银行名称" required>
                                        <div class="invalid-feedback">
                                            请输入银行名称
                                        </div>
                                    </div>
                                </div>
                            </div>

                           <!-- 在银行卡号输入字段部分，修改为： -->
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="bank_card_number" class="form-label">
                                            <i class="bi bi-credit-card text-primary"></i> 银行卡号 <span class="text-danger">*</span>
                                        </label>
                                        <input type="text" class="form-control" id="bank_card_number" name="bank_card_number" 
                                               value="<?php echo htmlspecialchars($userInfo['bank_card_number'] ?? ''); ?>" 
                                               placeholder="请输入银行卡号（纯数字）" required 
                                               pattern="\d{16,23}" 
                                               oninput="formatBankCard(this)"
                                               maxlength="23">
                                        <div class="invalid-feedback">
                                            请输入正确的银行卡号（16-19位数字）
                                        </div>
                                    </div>
                                </div>
                            </div>
                                                        
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-save"></i> 保存基本信息
                            </button>
                        </form>
                    </div>

                    <!-- 密码修改 -->
                    <div class="mb-5">
                        <h5 class="border-bottom pb-2 mb-3">
                            <i class="bi bi-key"></i> 密码修改
                        </h5>
                        <form method="POST" class="needs-validation" novalidate>
                            <input type="hidden" name="action" value="change_password">
                            <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="old_password" class="form-label">原密码</label>
                                        <input type="password" class="form-control" id="old_password" name="old_password" required>
                                        <div class="invalid-feedback">
                                            请输入原密码
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="new_password" class="form-label">新密码</label>
                                        <input type="password" class="form-control" id="new_password" name="new_password" required minlength="8">
                                        <div class="invalid-feedback">
                                            密码长度不能少于8位
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="confirm_password" class="form-label">确认新密码</label>
                                        <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                                        <div class="invalid-feedback">
                                            请确认新密码
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <button type="submit" class="btn btn-warning">
                                <i class="bi bi-key-fill"></i> 修改密码
                            </button>
                        </form>
                    </div>

                    <!-- 收款码管理 -->
                    <div class="mb-5">
                        <h5 class="border-bottom pb-2 mb-3">
                            <i class="bi bi-qr-code"></i> 收款码管理
                        </h5>
                        
                        <div class="row">
                            <!-- 微信收款码 -->
                            <div class="col-md-6 mb-4">
                                <div class="card">
                                    <div class="card-header bg-success text-white">
                                        <i class="bi bi-wechat"></i> 微信收款码
                                    </div>
                                    <div class="card-body text-center">
                                        <?php if ($userInfo['wechat_qr']): ?>
                                            <img src="<?php echo UPLOAD_URL . 'qrcodes/' . $userInfo['wechat_qr']; ?>" 
                                                 alt="微信收款码" class="img-fluid mb-3" style="max-height: 200px;">
                                            <p class="text-muted small">当前已上传微信收款码</p>
                                        <?php else: ?>
                                            <div class="bg-light rounded p-4 mb-3">
                                                <i class="bi bi-qr-code-scan" style="font-size: 3rem; color: #6c757d;"></i>
                                                <p class="text-muted mt-2">暂未上传微信收款码</p>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <form method="POST" enctype="multipart/form-data" class="mt-3">
                                            <input type="hidden" name="action" value="update_qr">
                                            <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                            <input type="hidden" name="qr_type" value="wechat">
                                            <div class="mb-3">
                                                <input type="file" class="form-control" name="qr_image" 
                                                       accept="image/*" required>
                                                <div class="form-text">支持 JPG、PNG、GIF 格式，最大 5MB</div>
                                            </div>
                                            <button type="submit" class="btn btn-success btn-sm">
                                                <i class="bi bi-upload"></i> 上传微信收款码
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 支付宝收款码 -->
                            <div class="col-md-6 mb-4">
                                <div class="card">
                                    <div class="card-header bg-primary text-white">
                                        <i class="bi bi-alipay"></i> 支付宝收款码
                                    </div>
                                    <div class="card-body text-center">
                                        <?php if ($userInfo['alipay_qr']): ?>
                                            <img src="<?php echo UPLOAD_URL . 'qrcodes/' . $userInfo['alipay_qr']; ?>" 
                                                 alt="支付宝收款码" class="img-fluid mb-3" style="max-height: 200px;">
                                            <p class="text-muted small">当前已上传支付宝收款码</p>
                                        <?php else: ?>
                                            <div class="bg-light rounded p-4 mb-3">
                                                <i class="bi bi-qr-code-scan" style="font-size: 3rem; color: #6c757d;"></i>
                                                <p class="text-muted mt-2">暂未上传支付宝收款码</p>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <form method="POST" enctype="multipart/form-data" class="mt-3">
                                            <input type="hidden" name="action" value="update_qr">
                                            <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                            <input type="hidden" name="qr_type" value="alipay">
                                            <div class="mb-3">
                                                <input type="file" class="form-control" name="qr_image" 
                                                       accept="image/*" required>
                                                <div class="form-text">支持 JPG、PNG、GIF 格式，最大 5MB</div>
                                            </div>
                                            <button type="submit" class="btn btn-primary btn-sm">
                                                <i class="bi bi-upload"></i> 上传支付宝收款码
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- PushPlus设置 -->
                    <div class="mb-4">
                        <h5 class="border-bottom pb-2 mb-3">
                            <i class="bi bi-bell"></i> 推送通知设置
                        </h5>
                        <form method="POST">
                            <input type="hidden" name="action" value="update_pushplus">
                            <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                            
                            <div class="mb-3">
                                <label for="pushplus_token" class="form-label">
                                    PushPlus密钥
                                    <a href="http://www.pushplus.plus/" target="_blank" class="small text-decoration-none">
                                        <i class="bi bi-question-circle"></i> 如何获取？
                                    </a>
                                </label>
                                <input type="text" class="form-control" id="pushplus_token" name="pushplus_token" 
                                       value="<?php echo htmlspecialchars($userInfo['pushplus_token']); ?>"
                                       placeholder="请输入您的PushPlus密钥">
                                <div class="form-text">
                                    获取密钥后，您将收到订单状态变更的推送通知
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="pushplus_enabled" name="pushplus_enabled" 
                                           value="1" <?php echo $userInfo['pushplus_enabled'] ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="pushplus_enabled">
                                        开启推送通知
                                    </label>
                                </div>
                            </div>
                            
                            <button type="submit" class="btn btn-info text-white">
                                <i class="bi bi-bell-fill"></i> 保存推送设置
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// 密码确认验证
document.getElementById('confirm_password').addEventListener('input', function() {
    const newPassword = document.getElementById('new_password').value;
    const confirmPassword = this.value;
    
    if (newPassword !== confirmPassword) {
        this.setCustomValidity('密码不一致');
    } else {
        this.setCustomValidity('');
    }
});
// 银行卡号格式化函数（实时格式化显示，但存储纯数字）
function formatBankCard(input) {
    // 获取光标位置
    let cursorPos = input.selectionStart;
    
    // 移除所有非数字字符
    let value = input.value.replace(/\D/g, '');
    
    // 格式化显示：每4位加一个空格
    let formattedValue = '';
    for (let i = 0; i < value.length; i++) {
        if (i > 0 && i % 4 === 0) {
            formattedValue += ' ';
        }
        formattedValue += value[i];
    }
    
    // 更新输入框值
    input.value = formattedValue;
    
    // 调整光标位置（考虑新增的空格）
    let addedSpaces = Math.floor(cursorPos / 4);
    let newCursorPos = cursorPos + addedSpaces;
    input.setSelectionRange(newCursorPos, newCursorPos);
}

// 在表单提交前，移除银行卡号中的空格
document.addEventListener('DOMContentLoaded', function() {
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            const bankCardInput = form.querySelector('#bank_card_number');
            if (bankCardInput) {
                // 移除所有空格，只保留纯数字
                bankCardInput.value = bankCardInput.value.replace(/\s/g, '');
            }
        });
    });
});

// 页面加载时，如果已有银行卡号，进行格式化显示
document.addEventListener('DOMContentLoaded', function() {
    const bankCardInput = document.getElementById('bank_card_number');
    if (bankCardInput && bankCardInput.value) {
        formatBankCard(bankCardInput);
    }
});

// 表单验证
(function() {
    'use strict';
    window.addEventListener('load', function() {
        const forms = document.querySelectorAll('.needs-validation');
        Array.prototype.filter.call(forms, function(form) {
            form.addEventListener('submit', function(event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    }, false);
})();
</script>

<?php include __DIR__ . '/footer.php'; ?>